<?php
/**
 * Created by PhpStorm.
 * User: tiemeng
 * Date: 16/3/21
 * Time: 20:04
 */
class orderController extends base{
    public function __construct($type='api')
    {
        if(common::request('a') == "payDone"){
            parent::__construct('show');
        }else {
            parent::__construct($type);
            $this->in_user();
            if(empty($this->uid)){
                $_ENV['error']->getErrors(201);
                exit;
            }
        }
    }
    /**
     * 新建/修改收货地址
     */
    public function doconsignee(){
        $name = common::request('name','P','',true);
        $phone = common::request('phone','P','',true);
        $province = common::request('province','P','',true);
        $city = common::request('city','P','',true);
        $district = common::request('district','P','',true);
        $address = common::request('address','P',true);
        $is_default = common::request('is_default','P',0,true);
        $addtime = time();
        if(empty($name) || empty($phone) || empty($province) || empty($city) || empty($district) || empty($address)){
            $_ENV['error']->getErrors(101);
            exit;
        }
        $uid = $this->uid;
        $this->in_erpDb();
        $insertData = compact('name','uid','phone','province','city','district','address','is_default','addtime');
        $id = common::request('id','P','',true);
        if(!empty($id)){
            $insertData['id'] = $id;
        }
        $insertId = $this->erpDb->insertRowTable('r_consignee',$insertData);
        (!empty($id)) && $insertId = $id;
        if($is_default == 1){
            $this->erpDb->query("update r_consignee set is_default=0 where uid='$uid' and id != '$insertId'");
        }
        $this->result['result']['id'] = $insertId;
    }

    /**
     * 删除收货人地址
     */
    public function dodelConsignee()
    {
        $id = common::request('id',"G",'',true);
        if(empty($id)){
            $_ENV['error']->getErrors(101);
            exit;
        }
        $this->in_erpDb();
        $this->erpDb->query("update r_consignee set status=1 where id='$id'");
        $this->result['result']['is_success'] = 1;
    }

    /**
     * 收货人列表
     */
    public function doconsigneeList(){
        $uid = $this->uid;
        if(empty($uid)){
            $_ENV['error']->getErrors(201);
            exit;
        }
        $data = $this->load('order')->getConsigneeList($uid);
        $this->result['result']['list'] = $data;
    }

    /**
     * 购买商品
     */
    public function doorder(){
        $atype = common::request('atype','R');
        $uid = $this->uid;
        $goods_id = common::request('goods_id','R','',true);
        $num = common::request('num','R',1,true);
        $consignee_id = common::request('consignee_id','R',0,true);
        $aid = common::request('aid','R','',true);
        $mark = common::request('mark',"R",'',true);//订单备注
        $gid = common::request('gid','R','',true);
        
        $atype = common::request('atype','R');
        $match_id = common::request('match_id','R');
        $goods = common::request('goods','R');
        
    	if(!$uid)
        {
            $_ENV['error']->getErrors(201);
            exit;
        }
        if(!in_array($atype, array('liveSignUp', 'liveTopUp')) && empty($consignee_id)){
            $_ENV['error']->getErrors(101);
            exit;
        }
        if(!($goods_id && $num) && !($goods && common::is_json($goods))){
            $_ENV['error']->getErrors(101);
            exit;
        }

        $order_mod = $this->load('order');
        $goods_mod = $this->load('goods');
        $total_fee = 0;
        $cost = 0;
        $goods_fee = 0;
        $shipping_fee = 0;
        $discount = 1;
        $discountInfo = [];
        $fee_goods_id = 0;
        $goods = [];
        $now = time();
        $expireTime = $now+900;
        if($atype){
            if(!$match_id && !($atype && $aid)){
                $_ENV['error']->getErrors(101);
                exit;
            }
            if($atype == 'match'){
                $match_id = $aid;
                $matchInfo = $this->load('match')->getMatchInfo($aid);
                if($expireTime > $matchInfo['stime']){
                    $expireTime = $matchInfo['stime'];
                }
                $discountInfo = $matchInfo['discount'];
                $fee_goods_id = $matchInfo['fee_goods_id'];
            } else if ($atype == 'flashSales') {
                /*$flashSalesId = $aid;
                $arrFlashInfo = $this->load('flashBuy')->getFlashBuyInfo($flashSalesId,'id,status,express_fee'); //查询闪购状态
                if (!$arrFlashInfo) {
                    $_ENV['error']->getErrors(101);
                    exit;
                }
                if ($arrFlashInfo['status'] <> 5) {
                    $_ENV['error']->getErrors(5001);
                    exit;
                }*/
                $intOrderCnt = $this->load('order')->getNoPayOrderNum($uid,5);//查询用户未取消的商品订单数量
                if ($intOrderCnt > 0) {
                    $_ENV['error']->getErrors(3008);
                    exit;
                }
                $arr = array_unique(explode(",",$goods_id));
                $shipping_fee = 0;
                $express_arr = [];
                $num2 = explode(',',$num);
                if(empty($num2)){
                    $num2 = array_fill(0,count($arr),1); //默认为一件
                }
                $haitao = array();
                foreach ($arr as $k=>$v){
                    $goodsInfo = $goods_mod->getFlashGoodsInfo($v);
                    $express_arr[$goodsInfo['product']['id']] = $goodsInfo;
                    //海淘商品 实时查询运费价格
                    if(strpos($goodsInfo['product']['code'],"HT_")!==false){
                        $tmp = $goods_mod->getHaitaoPidGid($v);
                        $tmp['number'] = $num2[$k];
                        $haitao[] = $tmp;
                    }
                }
                if(empty($haitao)) {
                    foreach ($express_arr as $v) {
                        $shipping_fee += $v['product']['express_fee'];
                    }
                }else{
                    $fee = $this->load('shihuo')->calculateOrderPrices($haitao);
                    $shipping_fee = $fee->national_express_fee + $fee->local_express_fee + 10;
                }
            } elseif($atype == 'liveSignUp') {//微课报名
                $liveId = $aid;
                $arrLiveInfo = $this->load('live/live')->getLiveInfo($liveId,'id,status, price'); //查询闪购状态
                if (!$arrLiveInfo || $arrLiveInfo['price'] <=0) {
                    $_ENV['error']->getErrors(101);
                    exit;
                }
                if (in_array($arrLiveInfo['status'], array(liveModel::CANCEL_STATUS, liveModel::OVER_STATUS))) {
                    $_ENV['error']->getErrors(8006);
                    exit;
                }
                //一个用户只能报名一次--暂放
            } else if($atype == 'liveTopUp') {//微课充值
                $goldConfigId = $aid;
                $goldConfiguration = common::$goldConfiguration;
                if (!array_key_exists($goldConfigId, $goldConfiguration)) {
                    $_ENV['error']->getErrors(101);
                    exit;
                }
            }
            //商品
            $goods_ids = explode(',',$goods_id);
            $goods_num = 0;

            if ($atype == 'flashSales') {
                $num = explode(',',$num);
                if(empty($num)){
                   $num = array_fill(0,count($goods_ids),1); //默认为一件
                }
                //检测商品，计算价格
                //if (count($goods_ids) > 1) {//只允许买一件
                    //$_ENV['error']->getErrors(101);
                    //exit;
                //}
                foreach($goods_ids as $k=>$id){
                    $_num = isset($num[$k]) ? $num[$k] : 1;
                    //if ($_num <> 1) {
                    //    $_ENV['error']->getErrors(101);//只允许买一件
                    //    exit;
                    //}
                    $goodsInfo = $goods_mod->getFlashGoodsInfo($id);
                    if (!$goodsInfo) {
                        $_ENV['error']->getErrors(101);
                        exit;
                    }
                    $price = $goodsInfo['goodsInfo']['saleprice'];
                    $goods[] = [
                        'id'=>$id,
                        'num'=>$_num,
                        'price'=>$price,
                    ];
                    $surplusNum = bcsub($goodsInfo['goodsInfo']['stockNum'],$goodsInfo['goodsInfo']['saleNum']);//剩余库存
                    if($surplusNum < $_num){
                        $_ENV['error']->getErrors(3001);
                        exit;
                    }
                    //普通商品
                    $goods_fee += $price*$_num;
                    $goods_num += $_num;
                }
                $num = $goods_num;
                $goods_id = 0;
            } elseif($atype == 'liveSignUp') {//微课报名
                $num = 1; //默认为一件
                $price = $arrLiveInfo['price'];
                $goods[] = [
                    'id'=>$liveId,
                    'num'=>$num,
                    'price'=>$price,
                ];
                $goods_fee = $price*$num;
                $goods_id = 0;
            } else if($atype == 'liveTopUp') {//微课充值
                $num = 1; //默认为一件
                $price = $goldConfiguration[$goldConfigId]['costPrice'];
                $goods[] = [
                    'id'=>$goldConfigId,
                    'num'=>$num,
                    'price'=>$price,
                ];
                $goods_fee = $price*$num;
                $goods_id = 0;
            } else {
                $num = array_fill(0,count($goods_ids),1); //默认为一件
                $aid = 0;
                //检测商品，计算价格
                foreach($goods_ids as $k=>$id){
                    $_num = isset($num[$k]) ? $num[$k] : 1;
                    $goodsInfo = $goods_mod->getRaceGoodsInfo($id);
                    $surplusNum = bcsub($goodsInfo['goodsInfo']['stockNum'],$goodsInfo['goodsInfo']['saleNum']);//剩余库存
                    if($surplusNum < $_num){
                        $_ENV['error']->getErrors(3001);
                        exit;
                    }
                    $price = $goodsInfo['goodsInfo']['saleprice'];
                    $goods[] = [
                        'id'=>$id,
                        'num'=>$_num,
                        'price'=>$price,
                    ];
                    //报名费
                    if($id == $fee_goods_id){
                        $cost = $goodsInfo['goodsInfo']['saleprice'];
                        continue;
                    }
                    //普通商品
                    $goods_fee += $price*$_num;
                    $goods_num += $_num;
                }
                //商品减库存
                foreach($goods_ids as $k=>$id){
                    $goods_mod->saleRaceGoods($id, $num[$k]);
                }
                $_goods_fee = $goods_fee;
                //计算折扣
                $_last_num = 0;
                foreach($discountInfo as $row){
                    if($goods_num >= $row['num'] && $row['num'] > $_last_num){
                        $discount = $row['discount'];
                        $_goods_fee = $goods_fee*$discount;
                        $_last_num = $row['num'];
                    }
                }
                $goods_fee = $_goods_fee;
                $num = $goods_num;
                $goods_id = 0;
            }
        }else{
            $stime = intval($this->redis->hget(REDIS_PREFIX.'ActivityInfo_'.$aid,'stime'));
            $expireTime > $stime && $expireTime = $stime;
            if($stime < time()){
                $_ENV['error']->getErrors(3004);
                exit;
            }
            $userOrder = $order_mod->getOrderByAid($uid,$aid);
            if(!empty($userOrder)){
                if($userOrder['uid'] == $uid && $userOrder['gid'] == $gid){
                    $_ENV['error']->getErrors(3003);
                    exit;
                }
            }
            
            $goodsInfo = $goods_mod->getGoodsById($goods_id);
            if(!$goods_mod->checkNum($goods_id,$num)){
                $_ENV['error']->getErrors(3001);
                exit;
            }
            //活动费用
            $cost = $this->redis->hget(REDIS_PREFIX."ActivityInfo_".$aid,'cost');
            $price = $goodsInfo['price'];
            $time = time();
            //如果是促销价格则为促销价 && 促销价格是否在促销时间内
            if($goodsInfo['is_pro'] && (($time >= $goodsInfo['pro_stime'] && $time <= $goodsInfo['pro_etime']) || ($goodsInfo['pro_stime'] == 0 && $goodsInfo['pro_etime'] == 0))){
                $price = $goodsInfo['pro_price'];
            }
            $goods_fee = $price * $num;
        }

        $name = '';
        $province = '';
        $city = '';
        $district = '';
        $address = '';
        $phone = '';
        if (!in_array($atype, array('liveSignUp', 'liveTopUp'))) {
            $consigneeInfo = $order_mod->getConsigneeById($consignee_id);
            if(!$consigneeInfo){
                $_ENV['error']->getErrors(3005);
                exit;
            }
            $name = $consigneeInfo['name'];
            $province = $consigneeInfo['province'];
            $city = $consigneeInfo['city'];
            $district = $consigneeInfo['district'];
            $address = $consigneeInfo['address'];
            $phone = $consigneeInfo['phone'];
        } else {
            $consignee_id = 0;
        }

        $total_fee = $cost + $goods_fee + $shipping_fee;
        
        $insertData = compact('uid','goods_id','num','consignee_id','shipping_fee','price','aid','total_fee','mark','gid','name','province','city','district','address','phone','goods','discount','expireTime');
        if($atype == 'match'){
            $insertData['match_id'] = $match_id;
            $orderId = $this->load('order')->addMatchOrder($insertData);
        }elseif($atype == 'marathon'){
            $orderId = $this->load('order')->addMarahonOrder($insertData);
        }elseif($atype == 'flashSales') {
            $orderId = $this->load('order')->addFlashSalesOrder($insertData);
            //删除购物车商品 购物车aid为固定值1
            if(!empty($orderId)&&$aid==1){
                $this->load('gear')->delshopcart($uid,implode(",",$goods_ids));
            }
        }elseif(in_array($atype, array('liveSignUp', 'liveTopUp'))) {
            $orderId = $this->load('order')->addLiveOrder($insertData, $atype);
        }else{
            $orderId = $order_mod->addOrder($insertData);
        }
        $this->result['result']['order_id'] = $orderId;
    }

    /**
     * 获取用户订单列表
     */
    public function doorderList(){
        $type = common::request('type','G',0,true);
        if(!in_array($type,[0,1,2])){
            $_ENV['error']->getErrors(101);
            exit;
        }
        $list = $this->afterVersion('2.8.8', '2.8.8') ? $this->load('order')->getOrderByUid($this->uid,$type) : [];
        
        $this->result['result']['list'] = $list;
    }

    /**
     * 商品详情页
     */
    public function _goodsDetail27(){
        $goodsId = common::request('goods_id','G','',true);
        $aid = common::request('aid',"G",'',true);
        $gid = common::request('gid','G','',true);
        $etime = $cost = $stime = $price = 0;
        $title = $subTitle = $thumb = $goodsName = '';
        $actInfo = $this->load('groupActivity')->getActByAid($aid);
        if(!empty($aid)){
            $stime = $actInfo['stime'];
            $etime = $actInfo['etime'];
            $title = $actInfo['title'];
            $subTitle = isset($actInfo['short_desc']) ? $actInfo['short_desc'] : '';
            $cost = $actInfo['cost'];
            $thumb = $actInfo['img'];
        }
        $goods = $this->load('goods')->getGoodsById($goodsId);
        $uid = $this->uid;
        $consignee = $this->erpDb->getAll("select id,name,phone,province,city,district,address,is_default from r_consignee where uid = '$uid' and status=0 order by is_default desc,id asc limit 1");
        if(empty($consignee) && empty($goods)){
            $consignee = $this->db->getAll("select name,phone from r_collect_info where uid='$uid' order by id desc limit 1");
            foreach($consignee as &$item){
                $item['id'] = $item['province'] = $item['city'] = $item['district'] = $item['address'] = $item['is_default'] = '';
            }
        }
        if(!empty($goods)){
            $thumb = $goods['thumb'];
            $goodsName = $goods['goods_name'];
            $subTitle = $actInfo['title'];
        }
        $goodsInfo = [
            'title'      => $title,
            'thumb'      => $thumb,
            'stime'      => $stime,
            'etime'      => $etime,
            'subTitle'   => $subTitle,
            //商品相关
            'goodsId'    => $goodsId,
            'goodsName'  => $goodsName,
            'groupName'  => $this->redis->hget(REDIS_PREFIX."GroupInfo_".$gid,'name'),
            'price'      => $cost,
            'goodsType'  => empty($goods) ? 1 : 2 //1：不包含奖品 2：代表含有奖品
        ];
        $shipping = $this->load('order')->getShippingList(['id','shipping_code','shipping_name','shipping_fee']);
        $this->result['result'] = compact('consignee','goodsInfo','shipping');
    }

    /**
     * 订单详情
     */
    public function doorderDetail(){
        $order_id = common::request('order_id','G','',true);
        if(empty($order_id)){
            $_ENV['error']->getErrors(101);
            exit;
        }
        $uid = $this->uid;
        if(empty($uid)){
            $_ENV['error']->getErrors(201);
            exit;
        }
        $order_info = $this->load('order')->getOrderDetail($uid,$order_id);
        if(empty($order_info)){
            $_ENV['error']->getErrors(3006);
            exit;
        }

        //payment
        $pay = $this->loadLib('payment');
        $_paymentList = $pay->getApi('getPayList');
        $paymentList = [];
        
        $isInWeixin = common::isInWeixin();
        $isInAppWebview = common::isInAppWebview();
        foreach($_paymentList as $pay){
            //在微信
            if($isInWeixin && $pay['payment_type']==12){
                $paymentList[] = $pay;
            //在app
            }elseif($this->initType == 'api' && in_array($pay['payment_type'],[1,11])){
                $paymentList[] = $pay;
            //在web
            }elseif(!$isInWeixin && $this->initType == 'show' && $pay['payment_type'] == 2){
                $paymentList[] = $pay;
            }
        }
        $this->result['result']['orderInfo'] = $order_info;
        $this->result['result']['paymentList'] = $paymentList;
    }

    /**
     * 付款
     */
    public function dopay(){
        $orderId = common::request('order_id','G','',true);
        $payment_type = common::request('payment_type','G','1');
        $now = time();
        $orderInfo = $this->load('order')->getOrderByOrderId($orderId);
        if(empty($orderInfo)){
            $_ENV['error']->getErrors(101);
            exit;
        }
        if($now>$orderInfo['expireTime']){
            $_ENV['error']->getErrors(3007);
            exit;
        }
        
        $totalFee = $orderInfo['total_fee'];
        $outMinute = 0;
        $subject = '虎扑跑步订单';
        $callback_url = '';
        $show_url = '';
        $return_url = '';
        
        if($orderInfo['match_id']){
            //赛事
            $match_id = $orderInfo['match_id'];
            $actInfo = $this->load('match')->getMatchInfo($match_id);
            $totalFee = $orderInfo['total_fee'];
            $subject = "虎扑跑步赛事订单-".$actInfo['name'];
            $outMinute = 60*24;
            $callback_url = "http://".$this->config['host']."/order/payDone?order_id=".$orderId;
            //$show_url = 'http://'.$this->config['host']."/show/matchInfo?match_id=".$match_id;
            $show_url = 'http://'.$this->config['host']."/show/paySuccess?order_id={$orderId}";
            $return_url = "http://".$this->config['host']."/order/payDone?order_id=".$orderId;
        }else if($orderInfo['act_id'] && $orderInfo['act_type'] == 2){ //马拉松活动
            $actInfo = $this->db->getRowTable('r_activity_marathon', ['start_time', 'title'], 'id=' . $orderInfo['act_id']);
            if(empty($actInfo) || $now > $actInfo['start_time']){
                $_ENV['error']->getErrors(3004);
                exit;
            }
            $totalFee = $orderInfo['total_fee'];
            $outMinute = $actInfo['start_time'] > 0 ? intval(($actInfo['start_time'] - $orderInfo['addtime'])/60) : 30;
            $subject = "虎扑跑步马拉松订单-".$actInfo['title'];
            $callback_url = "http://".$this->config['host']."/order/payDone";
            $show_url = 'http://'.$this->config['host']."/marathonWeb/marathonRaceNum/?m_id=".$orderInfo['act_id'];
            $return_url = "http://".$this->config['host']."/order/payDone";
        }elseif($orderInfo['act_type'] == 5 || $orderInfo['act_type'] == 8){
            $totalFee = $orderInfo['total_fee'];
            //$flashSale = $this->load('flashBuy')->getFlashBuyInfo($orderInfo['act_id'],'title');
            //$subject = "虎扑跑步订单-".($flashSale ? $flashSale['title'] : '');
            $outMinute = 60*24;
            $callback_url = "http://".$this->config['host']."/order/payDone";
            $return_url = "http://".$this->config['host']."/order/payDone?order_id=".$orderId;
        }elseif($orderInfo['act_type'] == 6){//微课报名
            $totalFee = $orderInfo['total_fee'];
            $subject = "微课报名-".json_encode($this->load('live/live')->getLiveInfo($orderInfo['act_id'],'id,title'));
            $outMinute = 60*24;
            $callback_url = "http://".$this->config['host']."/order/payDone";
            $return_url = "http://".$this->config['host']."/order/payDone?order_id=".$orderId;
        }elseif($orderInfo['act_type'] == 7){//微课充值
            $totalFee = $orderInfo['total_fee'];
            $subject = "微课元宝充值-".json_encode(common::$goldConfiguration[$orderInfo['act_id']]);
            $outMinute = 60*24;
            $callback_url = "http://".$this->config['host']."/order/payDone";
            $return_url = "http://".$this->config['host']."/order/payDone?order_id=".$orderId;
        }else{
            $goodsInfo = $this->load('goods')->getGoodsById($orderInfo['goods_id']);
            if(!empty($goodsInfo)){
                $title = $goodsInfo['goods_name'];
            }else{
                $title = $this->redis->hget(REDIS_PREFIX.'ActivityInfo_'.$orderInfo['aid'],'title');
            }
            $outMinute = $stime > 0 ? intval((($stime-$orderInfo['addtime'])/60)) : 60;
            $subject = "群组活动-".$title;
            $callback_url = "http://".$this->config['host']."/order/payDone";
        }
        
        $pay = $this->loadLib('payment');
        $data = [
            'payment_type' => $payment_type,
            'order_id'     => $orderId,
            'price'        => $totalFee,
            'subject'      => $subject,
            'uid'          => $this->uid,
            'body'         => '',
            'out_minute'   => $outMinute.'m',
            'callback_url' => $callback_url,
            'pub_openid'   => $this->load('user')->getWxPubOpenId(),
            'client_ip'    => common::getip(),
            'show_url'     => $show_url,
            'return_url'   => $return_url,
        ];
        $res = $pay->getApi('createOrder',$data);
        if($payment_type == 1){
            $res['param'] = isset($res['pay_str']) ? $res['pay_str'] : '';
        }
        $this->result['result'] = $res;
    }

    /**
     * IOS ApplePay 回调接口
     */
    public function doapplePayDone() {
        $uid = $this->uid;
        if(!$uid){
            $_ENV['error']->getErrors(201);
            exit;
        }
        $orderId = common::request('orderId','P','',true);
        if(!$orderId){
            $_ENV['error']->getErrors(101);
            exit;
        }
        $orderInfo = $this->load('order')->getRaceOrderInfoForWaitSend($orderId);
        if(empty($orderInfo) || ($orderInfo['uid'] <> $uid) || ($orderInfo['act_type'] <>7) ){
            $_ENV['error']->getErrors(3006);
            exit;
        }
        $appleStr = common::request('receipts','P','');
        if(!$appleStr){
            $_ENV['error']->getErrors(101);
            exit;
        }
        //信息验证
        $validData = $this->loadLib('iap')->getReceiptData($appleStr, 15,  TRUE);
        if (!$validData) {
            $_ENV['error']->getErrors(3009);
            exit;//信息无效
        }
        $this->in_erpDb();
        $time = time();
        $this->erpDb->query("update r_order set status=4,paytime=$time,pay_status = 20 where order_id='$orderId' ");
        if($orderInfo['act_type'] == 7) {//记录元宝充值流水
            $this->load('live/live')->addGoldCostLog(0, $uid, 3, 0, $orderInfo['gold_num'], $orderInfo['id'], $orderInfo['price'], 1 , $orderInfo['give_gold_num']);
        }
        $this->result['result']['is_success'] = 1;
    }


    /**
     * 支付完成
     */
    public function dopayDone(){
        $orderId = common::request('order_id','G','',true);
        $status = common::request('status','G');
        $sign = common::request('sign','G');
        $orderInfo = $this->load('order')->getOrderByOrderId($orderId);
        if(empty($orderInfo)){
            return false;
        }
        $pay = $this->loadLib('payment');
        if(!$pay->verifySign(['order_id'=>$orderId,'status'=>$status,'sign'=>$sign])){
            //return false;
        }
        $uid = $orderInfo['uid'];
        $aid = $orderInfo['aid'];
        $gid = $orderInfo['gid'];
        $match_id = $orderInfo['match_id'];
        if($status == 2){
            $this->in_erpDb();
            $time = time();
            $this->erpDb->query("update r_order set paytime='$time',pay_status = 20 where order_id='$orderId' ");
            if($orderInfo['goods_id'] == 0 && $orderInfo['goods']==''){
                $this->erpDb->query("update r_order set status = 4 where order_id='$orderId' ");
            }
            if($orderInfo['act_type'] == 7) {//记录元宝充值流水
                $this->load('live/live')->addGoldCostLog(0, $uid, 3, 0, $orderInfo['gold_num'], $orderInfo['id'], $orderInfo['price'], 1 , $orderInfo['give_gold_num']);
            }
        }
        //赛事
        if(!empty($match_id)){
            if($status == 2){
                $match_mod = $this->load('match');
                $matchAddInfo = $match_mod->getMatchAdd($match_id,$uid,'user');
                $match_mod->updateAdd(['id'=>$matchAddInfo['user_add_id'],'status'=>1]);
            }
            //common::go('http://'.$this->config['host']."/show/matchInfo?match_id=".$match_id);
            common::go('http://'.$this->config['host']."/show/paySuccess?match_id=$match_id&status=$status&order_id=$orderId");
        }elseif (!empty($orderInfo['act_id']) && $orderInfo['act_type'] == 2 && $status == 2) { //马拉松活动订单
            exit;
        }

        //海淘闪购订单
        if($orderInfo['act_type']==8){
            $this->load('order')->createHaitaoOrder($orderInfo);
        }
        
        //群组活动
        if(!empty($aid) && !empty($gid) && $status == 2) {
            $actInfo = $this->load('groupActivity')->getActByAid($aid);
            if($actInfo['type'] == 2 || $actInfo['type'] == 4){
                $this->redis->ZINCRBY(REDIS_PREFIX.'GADay_'.$gid."_".$aid,0,$uid);
            }
            if($actInfo['type'] == 1 || $actInfo['type'] == 3){
                $this->redis->ZINCRBY(REDIS_PREFIX.'GARecord_'.$gid."_".$aid,0,$uid);
            }
            $redisKey = REDIS_PREFIX."GAJoin_".$gid."_".$aid;//参加活动
            $this->redis->zadd(REDIS_PREFIX."MYActivity_".$uid,$actInfo['stime'],$aid);
            if(!$this->redis->sismember(REDIS_PREFIX."ACTaccept_".$aid,$gid)){
                $hosts = $this->redis->hget(REDIS_PREFIX.'GroupHost',$gid);
                intval($this->redis->ssize($redisKey)) <=0 && $this->load('group')->sendMessage(array($hosts),$gid,'G15',0,$aid);
            }else{
                $this->load('group')->sendMessage(array($actInfo['uid']),$gid,'G11',0,$aid);
            }
            if(!$this->redis->sIsMember($redisKey,$uid)){
                $this->redis->sadd($redisKey,$uid);
                $time = time();
                $sql = "insert into r_activity_add(gid,uid,aid,add_time) values($gid,$uid,$aid,$time)";
                $this->db->query($sql);
            }
        }
    }

    public function queryOrder($orderId){
        $pay = $this->loadLib('payment');
        $info = $pay->getApi('queryOrder',['order_id'=>$orderId]);
        return $info;
    }

    /*
     * 跟踪快递
     */
    public function getKuaidiTrace(){
        $typeCom = common::request('typeCom','G');
        $typeNu = common::request('typeNu','G');
        $this->result['result'] = $this->load('kuaidi')->getTrace($typeCom,$typeNu);
    }
    
    /*
     * 赛事订单预览（确认，购物车）
     */
    public function dogoodsDetail(){
        if($this->afterVersion('2.8.1', '2.8.1')){
            $this->_goodsDetail28();
        }else{
            $this->_goodsDetail27();
        }
    }
    
    public function _goodsDetail28(){
        $goods_ids = common::request('goods_id','G');
        $atype = common::request('atype','G');
        $aid = common::request('aid','G');
        
        $uid = $this->uid;
        
        if(!$uid){
            $_ENV['error']->getErrors(201);
            exit;
        }
        
        //activity
        $aInfo = (object)[];
        $goodsList = [];
        $goods_mod = $this->load('goods');
        $total_fee = 0;
        $cost = 0;
        $shipping_fee = 0;
        $discount = 1;
        $discountInfo = [];
        $fee_goods_id = 0;
        $is_virtual = 0;
        $price_desc = '';
        $price = 0;
        $order_mod = $this->load('order');
        if($atype){
            if(!$aid || !$goods_ids){
                $_ENV['error']->getErrors(101);
                exit;
            }
            
            
            if($atype == 'match'){
                //赛事
                $aInfo = $this->load('match')->getMatchInfo($aid);
                $discountInfo = $aInfo['discount'];
                $fee_goods_id = $aInfo['fee_goods_id'];

                //商品
                $goods = explode(',',$goods_ids);
                $goods_num = 0;
                foreach($goods as $id){
                    $_num = 1;
                    $goodsInfo = $goods_mod->getRaceGoodsInfo($id);
                    if(empty($goodsInfo)){
                        continue;
                    }
                    $surplusNum = bcsub($goodsInfo['goodsInfo']['stockNum'],$goodsInfo['goodsInfo']['saleNum']);//剩余库存
                    if($surplusNum < $_num){
                        $_ENV['error']->getErrors(3001);
                        exit;
                    }
                    //报名费
                    if($id == $fee_goods_id){
                        $cost = $goodsInfo['goodsInfo']['saleprice'];
                        continue;
                    }
                    //购买数量
                    $goodsInfo['goodsInfo']['num'] = $_num;
                    
                    $goodsList[] = $goodsInfo;
                    $price += $goodsInfo['goodsInfo']['saleprice'];
                    $goods_num++;
                    if($goodsInfo['product']['is_virtual']){
                        $is_virtual = 1;
                    }
                }
                $_price = $price;
                foreach($discountInfo as $row){
                    if($goods_num >= $row['num']){
                        $discount = $row['discount'];
                        $_price = $price*$discount;
                    }
                }
                $price_desc = $order_mod->makePriceDesc($cost,$price,$discount);
                $price = $_price;
            }elseif($atype=='marathon'){
                //马拉松
            }elseif($atype == 'flashSales') {//闪购
                //$arrFlashInfo = $this->load('flashBuy')->getFlashBuyInfo($aid,'id,status,express_fee'); //查询闪购状态
                $shipping_fee = 0;
                
                //商品
                $goods = explode(',',$goods_ids);
                //if (count($goods) > 1) {//只允许买一件
                    //$_ENV['error']->getErrors(101);
                    //exit;
                //}
                $goods_num = 0;
                $_num = explode(',',common::request('num','G',1));
                if(empty($_num)){
                    $_num = array_fill(0,count($goods),1);
                }
                $express_arr = [];
                $haitao = array();
                foreach($goods as $k=>$id){
                    $goodsInfo = $goods_mod->getFlashGoodsInfo($id);
                    if(empty($goodsInfo)){
                        $_ENV['error']->getErrors(101);
                        exit;
                    }
                    $goodsInfo['goodsInfo']['num'] = $_num[$k];
                    $goodsList[] = $goodsInfo;
                    $price += $goodsInfo['goodsInfo']['saleprice']*$_num[$k];
                    $goods_num += $_num[$k];
                    if($goodsInfo['product']['is_virtual']){
                        $is_virtual = 1;
                    }
                    $surplusNum = bcsub($goodsInfo['goodsInfo']['stockNum'],$goodsInfo['goodsInfo']['saleNum']);//剩余库存
                    if($surplusNum < $_num[$k]){
                        $_ENV['error']->getErrors(3001);
                        exit;
                    }
                    $express_arr[$goodsInfo['product']['id']] = $goodsInfo;
                    if(strpos($goodsInfo['product']['code'],"HT_")!==false){
                        $tmp = $goods_mod->getHaitaoPidGid($id);
                        $tmp['number'] = $_num[$k];
                        $haitao[] = $tmp;
                    }
                }
                if(empty($haitao)) {
                    foreach ($express_arr as $v) {
                        $shipping_fee += $v['product']['express_fee'];
                    }
                }else{
                    $fee = $this->load('shihuo')->calculateOrderPrices($haitao);
                    $shipping_fee = $fee->national_express_fee + $fee->local_express_fee + 10;
                }
                $price_desc = $_goods_fee = $price;
            }
        }else{
            //群组活动
            $goodsId = $goods_ids;
            $gid = common::request('gid','G','',true);
            $etime = $cost = $stime = $price = 0;
            $title = $subTitle = $thumb = $goodsName = '';
            $aInfo = $this->load('groupActivity')->getActByAid($aid);
            if(!empty($aid)){
                $stime = $aInfo['stime'];
                $etime = $aInfo['etime'];
                $title = $aInfo['title'];
                $subTitle = isset($aInfo['short_desc']) ? $aInfo['short_desc'] : '';
                $cost = $aInfo['cost'];
                $thumb = $aInfo['img'];
            }
            $goods = $goods_mod->getGoodsById($goodsId);
            if(!empty($goods)){
                $thumb = $goods['thumb'];
                $goodsName = $goods['goods_name'];
                $subTitle = $aInfo['title'];
            }
            $goodsInfo = [
                'title'      => $title,
                'thumb'      => $thumb,
                'stime'      => $stime,
                'etime'      => $etime,
                'subTitle'   => $subTitle,
                //商品相关
                'goodsId'    => $goodsId,
                'goodsName'  => $goodsName,
                'groupName'  => $this->redis->hget(REDIS_PREFIX."GroupInfo_".$gid,'name'),
                'price'      => $cost,
                'goodsType'  => empty($goods) ? 1 : 2 //1：不包含奖品 2：代表含有奖品
            ];
            $is_virtual = empty($goods) ? 1 : 0;
            $goodsList[] = $goodsInfo;
        }
        
        //address
        $consigneeList = $order_mod->getConsigneeList($uid);
        
        //payment
        $pay = $this->loadLib('payment');
        $_paymentList = $pay->getApi('getPayList');
        $paymentList = [];
        
        $isInWeixin = common::isInWeixin();
        foreach($_paymentList as $pay){
            if($isInWeixin && $pay['payment_type']==12){
                $paymentList[] = $pay;
            }elseif($pay['payment_type']==2){
                $paymentList[] = $pay;
            }
        }
        
        //shipping
        $shippingList = $order_mod->getShippingList();
        if($is_virtual){
            foreach($shippingList as &$shipping){
                $shipping['shipping_fee'] = 0;
            }
        }
        
        $total_fee = $cost + $price + $shipping_fee;
        
        $this->result['result'] = compact('atype','aid','aInfo','consigneeList','goodsList','paymentList','shippingList','total_fee','is_virtual','discount','price','price_desc','cost','discountInfo','shipping_fee');
    }
    
    /*
     * 完成订单
     */
    public function dofinishOrder(){
        $order_id = common::request('order_id','P');
        $uid = $this->uid;
        if(empty($order_id)){
            $_ENV['error']->getErrors(101);
            exit;
        }
        if(!$uid){
            $_ENV['error']->getErrors(201);
            exit;
        }
        $this->load('order')->finishOrder($order_id,$uid);
    }
}